package other.edan.system.k3;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.rkhd.platform.sdk.ScheduleJob;
import com.rkhd.platform.sdk.api.annotations.RequestMethod;
import com.rkhd.platform.sdk.api.annotations.RestApi;
import com.rkhd.platform.sdk.api.annotations.RestMapping;
import com.rkhd.platform.sdk.api.annotations.RestQueryParam;
import com.rkhd.platform.sdk.data.model.Product;
import com.rkhd.platform.sdk.data.model.SyncConfig__c;
import com.rkhd.platform.sdk.exception.ApiEntityServiceException;
import com.rkhd.platform.sdk.exception.AsyncTaskException;
import com.rkhd.platform.sdk.exception.ScriptBusinessException;
import com.rkhd.platform.sdk.log.Logger;
import com.rkhd.platform.sdk.log.LoggerFactory;
import com.rkhd.platform.sdk.model.BatchOperateResult;
import com.rkhd.platform.sdk.model.OperateResult;
import com.rkhd.platform.sdk.model.QueryResult;
import com.rkhd.platform.sdk.param.ScheduleJobParam;
import com.rkhd.platform.sdk.service.FutureTaskService;
import com.rkhd.platform.sdk.service.XoqlService;
import com.rkhd.platform.sdk.task.FutureTask;
import org.apache.commons.lang.StringUtils;
import other.edan.system.client.EdanK3Utils;
import other.edan.system.utils.*;

import java.util.*;
import java.util.stream.Collectors;


/**
 * @Description 同步K3产品数据
 * @Author 黎炎松
 * 2024-06-19 13:53
 */
@RestApi(baseUrl = "/xsy/product")
public class SyncProduct extends SyncSuper implements ScheduleJob, FutureTask {
    private static XoqlService xoqlService = XoqlService.instance();
    private static final Logger logger = LoggerFactory.getLogger();
    private static String LOGGER_MSG = "定时同步K3产品数据 ==> ";

    // 执行定时任务
    @Override
    public void execute(ScheduleJobParam scheduleJobParam) {
        logger.debug(LOGGER_MSG + " 执行定时任务开始");
        try {
            String messageId = FutureTaskService.instance().addFutureTask(getClass(), "");
            logger.info(LOGGER_MSG + "异步ID:" + messageId);
        } catch (Exception e) {
            logger.error(LOGGER_MSG + " ----- 发生异常：" + e.getMessage());
        }
    }

    // 执行异步函数
    @Override
    public void execute(String s) throws ScriptBusinessException {
        startSyncProductData("");
    }

    /**
     * 根据产品编号手动触发产品同步
     * @param
     * @return
     */
    @RestMapping(value = "/syncK3ProductByNumber", method = RequestMethod.POST)
    public String syncK3ProductByNumber(@RestQueryParam(name = "id") Long productId) {

        // 获取产品的编码
        logger.debug("根据产品编号手动触发产品同步: " + productId);
        Product product = new Product();
        product.setId(productId);
        product = HCXObjectService.get(product);
        String fNumber__c = product.getFNumber__c();

        logger.debug("根据产品编号手动触发产品同步: " + fNumber__c);
        return startSyncProductData(fNumber__c);
    }

    /**
     * 手动触发产品同步
     * @param
     * @return
     */
    @RestMapping(value = "/syncK3Product", method = RequestMethod.POST)
    public String syncK3Product() throws AsyncTaskException {
        logger.debug("手动触发产品同步");
        String messageId = FutureTaskService.instance().addFutureTask(getClass(), "");
        logger.info(LOGGER_MSG + "异步ID:" + messageId);
        return TfReturnMsgTools.getSuccessResult("Start synchronizing data");
    }


    public static void main(String[] args) throws ApiEntityServiceException {
        //new SyncProduct().startSyncProductData("");
        new SyncProduct().startSyncProductData("90.83.61.AC1001");
    }

    /**
     * 开始同步产品数据
     */
    public String startSyncProductData(String productNumber) {
        try {
            logger.debug(LOGGER_MSG + "处理开始");

            // 从数据配置表中获取数据
            String sql = "select id,lastSyncTime__c,syncAssistVal__c from syncConfig__c where syncKey__c = 'K3_CPTB'";
            SyncConfig__c syncConfig = HCXObjectService.queryOne(sql);
            logger.debug(LOGGER_MSG + " syncConfig = " + syncConfig);
            if (syncConfig == null) {
                logger.debug(LOGGER_MSG + " 数据配置信息不存在");
                return TfReturnMsgTools.getFailResult("Data configuration information does not exist");
            }

            // 获取同步时间
            String startDate = syncConfig.getLastSyncTime__c();
            String endDate = HCDateUtils.dateToString(new Date(), HCDateUtils.FORMATTIME); // 同步结束时间
            if (StringUtils.isBlank(startDate)) {
                // 如果为空则退回1天前
                startDate = HCDateUtils.getDaysBeforeString(1, HCDateUtils.FORMATTIME);
            }
            // todo
            //startDate = "2023-08-18 00:00:00";
            //endDate = "2024-06-20 00:00:00";

            // 设置参数
            Map<String, Object> paramsMap = new HashMap<>();
            paramsMap.put("page", "1");
            paramsMap.put("pageSize", "500");
            // 产品编码如果不为空 则只入参产品编码
            if (StringUtils.isNotBlank(productNumber)) {
                paramsMap.put("productNumber", productNumber);
            } else {
                paramsMap.put("updateStartDate", startDate);
                paramsMap.put("updateEndDate", endDate);
            }
            logger.debug(LOGGER_MSG + " paramsMap: " + paramsMap);

            // 发送请求获取数据
            ResultBody response = EdanK3Utils.sendGet(paramsMap, EdanK3Utils.GET_PRODUCT_URL, "");
            if (!Objects.equals(response.getCode(), "200")) {
                logger.debug(LOGGER_MSG + "查询k3产品数据异常: " + response.getMessage());
                return TfReturnMsgTools.getFailResult("Abnormal query of K3 product data: " + response.getMessage());
            }

            // 获取产品数据 判断是否有值
            JSONObject result = (JSONObject) response.getResult();
            List<JSONObject> productList = JSONObject.parseArray(result.getJSONArray("productInfos").toJSONString(), JSONObject.class);
            logger.debug(LOGGER_MSG + "查询返回的数据: " + productList.size());
            if (productList.size() <= 0) {
                logger.debug(LOGGER_MSG + "暂无需要处理的数据");
                // 同步修改配置表
                upSysConfig(syncConfig, endDate, 0);
                return TfReturnMsgTools.getSuccessResult("There are no products that need to be synchronized");
            }

            // 获取选项通用集以及产品目录数据
            JSONArray unitPickList = ComUtils.getGlobalPicks("unit__c"); // 单位
            JSONArray productLinePick = ComUtils.getGlobalPicks("ERPproductLine__c"); // ERP产品线

            // 获取系统中的产品数据 判断是否已经存在
            String fnumbers = productList.stream().map(v -> "'" + v.getString("fnumber") + "'").collect(Collectors.joining(","));
            logger.debug(LOGGER_MSG + "fnumbers: " + fnumbers);
            sql = "select id,FNumber__c,fitemID__c from product where FNumber__c in (" + fnumbers + ")";
            Map<String, Long> crmProductMap =
                    xoqlService.query(sql, true).getRecords().stream().collect(Collectors.toMap(e -> e.getString("FNumber__c"), e1 -> e1.getLong("id"), (e, e1) -> e));
            logger.debug(LOGGER_MSG + "crmProductMap: " + crmProductMap);

            // 根据产品型号查询系统中是否存在，不存在则进行添加一条以产品型号命名的产品
            String productModels = productList.stream().filter(v -> v.getString("f_134") != null).map(v -> "'" + v.getString("f_134") + "'").collect(Collectors.joining(","));
            logger.debug(LOGGER_MSG + "productModels: " + productModels);
            sql = "select id,productName from product where productName in (" + productModels + ")";
            Map<String, Long> crmProductModelMap =
                    xoqlService.query(sql, true).getRecords().stream().collect(Collectors.toMap(e -> e.getString("productName"), e1 -> e1.getLong("id"), (e, e1) -> e));
            logger.debug(LOGGER_MSG + "crmProductModelMap: " + crmProductModelMap);

            // 获取新增、修改的数据
            List<Product> addProductList = new ArrayList<>();
            List<Product> upProductList = new ArrayList<>();
            for (JSONObject productObj : productList) {
                Product product = new Product();
                product.setEntityType(11010000400001L);
                product.setParentId(3420201629964840L); // 产品目录
                String fnumber = productObj.getString("fnumber");
                product.setFNumber__c(fnumber); // 物料代码
                product.setProductName(productObj.getString("fname")); // 物料名称
                product.setFitemID__c(productObj.getString("fitemID")); // 产品id
                product.setFscProductModel(productObj.getString("fmodel")); // 规格型号

                // ERP 产品线
                String f_105 = productObj.getString("f_105");
                product.setERPproductLine__c(ComUtils.getValueByApiKey(productLinePick, f_105));

                product.setProductRegistration__c(productObj.getString("f_127")); // 产品注册名称
                product.setRegistrationCertificate__c(productObj.getString("f_154")); // 产品注册证号
                product.setProductionLicense__c(productObj.getString("f_155")); // 产品许可证号
                String funitCode = productObj.getString("funitCode");
                product.setUnit__c(ComUtils.getValueByApiKey(unitPickList, funitCode)); // 单位

                // 判断注册型号
                String model = productObj.getString("f_134");
                product.setRegistrationModel__c(model); // 产品注册型号
                if (model != null && !crmProductModelMap.containsKey(model)) {
                    // 新增一条以产品型号命名的产品
                    Product addProduct = JSONObject.parseObject(product.toString(), Product.class);
                    addProduct.setProductName(model);
                    addProduct.setEntityType(3553488822472578L);
                    addProduct.setId(null);
                    addProduct.setFNumber__c(null);
                    addProduct.setRegistrationModel__c(null);
                    addProductList.add(addProduct);
                }

                // 判断系统中是否存在，存在则更新
                if (crmProductMap.containsKey(fnumber)) {
                    product.setId(crmProductMap.get(fnumber));
                    upProductList.add(product);
                } else {
                    // 新增
                    addProductList.add(product);
                }

                // 批量新增、更新
                if (addProductList.size() > 100) {
                    HCXObjectService.insertBatch(addProductList);
                    addProductList.clear();
                }
                if (upProductList.size() > 100) {
                    HCXObjectService.updateBatch(upProductList);
                    upProductList.clear();
                }
            }

            // 批量新增
            if (addProductList.size() > 0) {
                logger.debug(LOGGER_MSG + "新增的数据: " + addProductList.size());
                BatchOperateResult batchOperateResult = HCXObjectService.insertBatch(addProductList);
                if (!batchOperateResult.getSuccess()) {
                    logger.debug(LOGGER_MSG + "批量新增异常: " + batchOperateResult.getErrorMessage());
                    return TfReturnMsgTools.getFailResult("Add Exception:"  +batchOperateResult.getErrorMessage());
                }
            }

            // 批量修改
            if (upProductList.size() > 0) {
                logger.debug(LOGGER_MSG + "修改的数据: " + upProductList.size());
                BatchOperateResult batchOperateResult = HCXObjectService.updateBatch(upProductList);
                if (!batchOperateResult.getSuccess()) {
                    logger.debug(LOGGER_MSG + "批量修改异常: " + batchOperateResult.getErrorMessage());
                    return TfReturnMsgTools.getFailResult("Modify exceptions:"  +batchOperateResult.getErrorMessage());
                }
            }

            // 更新同步配置
            if (StringUtils.isBlank(productNumber)) {
                upSysConfig(syncConfig, endDate, productList.size());
            }

            logger.debug(LOGGER_MSG + "处理成功");
            return TfReturnMsgTools.getSuccessResult("Synchronization successful");
        } catch (Exception e) {
            logger.debug(LOGGER_MSG + "处理异常:" + e.getMessage());
            return TfReturnMsgTools.getFailResult("Synchronization exception:" + e.getMessage());
        }
    }



}
